package com.zuoye.experiment2.controller;

import com.zuoye.experiment2.entity.Skills;
import com.zuoye.experiment2.service.IHeroesService;
import com.zuoye.experiment2.entity.Heroes;
import com.zuoye.experiment2.service.ISkillsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author coolwen
 * @since 2024-05-08 16:35:01
 */
@Controller
@RequestMapping("/heroes")
@Slf4j
public class HeroesController {

    @Autowired
    IHeroesService heroService;

    @Autowired
    ISkillsService skillService;

    @GetMapping("/list")
    public ResponseEntity<List<Heroes>> SkillsList() {
        List<Heroes> heroes = heroService.list();
        return ResponseEntity.ok(heroes);
    }

    @GetMapping("/showheroes")
    public String listHeroes(Model model) {
        List<Heroes> heroes = heroService.list();
        model.addAttribute("showHeroes", heroes);
        return "heroes/showHeroes";
    }

    @GetMapping("/{id}")
    public String showHeroes(@PathVariable Integer id, Model model) {
        Heroes heroes = heroService.getById(id);
        List<Skills> skills = skillService.getByHeroesId(id);
        model.addAttribute("heroes", heroes);
        model.addAttribute("skills", skills);
        return "heroes/heroesDetails";
    }

    @GetMapping("/addheroes")
    public String addHeroesDorm(Model model) {
        return "/heroes/addHeroes";
    }

    @PostMapping("/addheroes")
    public String saveHeroes(@ModelAttribute("heroes") Heroes heroes) {
        heroService.save(heroes);
        return "redirect:/heroes/showheroes";
    }

    @GetMapping("/delete/{id}")
    public String deleteHero(@PathVariable Integer id) {
        heroService.removeById(id);
        return "redirect:/heroes/showheroes";
    }

    @GetMapping("/update/{id}")
    public String editHeroesForm(@PathVariable Integer id, Model model) {
        Heroes heroes = heroService.getById(id);
        model.addAttribute("updateHeroes", heroes);
        return "heroes/updateHeroes";
    }

    @PostMapping("/update/{id}")
    public RedirectView updateHeroes(@ModelAttribute("updateHeroes") Heroes heroes) {
        heroService.updateById(heroes);
        return new RedirectView("/heroes/showheroes");
    }

}
